package ca.usherbrooke.domus.sipnmove2.sip;

import java.util.Properties;

import javax.sip.ListeningPoint;
import javax.sip.PeerUnavailableException;
import javax.sip.SipFactory;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.address.AddressFactory;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;

/**
 * Register of the too many Jain-SIP API objects
 * 
 * Jain-SIP is a complicated API for SIP connectivity in Java, but it is quite complicated to manage, 
 * that is why we have created a simpler SIP interface.
 */
public class SipRegister {

	/**
	 * SIP provider
	 */
	private SipProvider sipProvider;
	
	/**
	 * SIP Header factory
	 */
	private HeaderFactory headerFactory;
	
	/**
	 * SIP address factory
	 */
	private AddressFactory addressFactory;
	
	/**
	 * SIP message factory
	 */
	private MessageFactory messageFactory;

	/**
	 * Default constructor
	 * @param ipAddress IP address
	 * @param port Port
	 */
	public SipRegister(String ipAddress, Integer port, String transport)
	{
		SipFactory sipFactory = SipFactory.getInstance();
		sipFactory.setPathName("gov.nist");

		// The port number is used as a Unique ID
		Properties properties = new Properties();
		properties.setProperty("javax.sip.STACK_NAME", "useragent" + port);
		// You need 16 for logging traces. 32 for debug + traces.
		// Your code will limp at 32 but it is best for debugging.
		properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
		properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "ua" + port + "_debug.txt");
		properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "ua" + port + "_log.txt");

		try {

			// Create SipStack object
			SipStack sipStack = sipFactory.createSipStack(properties);

			headerFactory = sipFactory.createHeaderFactory();
			addressFactory = sipFactory.createAddressFactory();
			messageFactory = sipFactory.createMessageFactory();

			ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress, port, transport);

			sipProvider = sipStack.createSipProvider(listeningPoint);

		} catch (PeerUnavailableException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Return the SIP provider
	 * @return sip provider
	 */
	public SipProvider getSipProvider()
	{
		return this.sipProvider;
	}

	/**
	 * Return the SIP header factory
	 * @return sip header factory
	 */
	public HeaderFactory getHeaderFactory()
	{
		return this.headerFactory;
	}

	/**
	 * Return the SIP address factory
	 * @return sip address factory
	 */
	public AddressFactory getAddressFactory()
	{
		return this.addressFactory;
	}

	/**
	 * Return the SIP message factory
	 * @return sip message factory
	 */
	public MessageFactory getMessageFactory()
	{
		return this.messageFactory;
	}
	
}
